package com.mayi.zds.service.imp;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.mayi.zds.config.AlipayConfig;
import com.mayi.zds.entity.PayBean;
import com.mayi.zds.service.PayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @ClassName AlipayServiceImpl
 * @Author zhong
 * @Date 2019/12/07 11:16:10
 * @Version 1.0
 */
@Service
public class AlipayServiceImpl implements PayService {
    @Autowired
    private AlipayConfig alipayConfig;

    @Override
    public String pay(PayBean payBean) {
        AlipayClient alipayClient = new DefaultAlipayClient(
                alipayConfig.getGatewayUrl(),
                alipayConfig.getApp_id(),
                alipayConfig.getAlipay_private_key(),
                "json",
                alipayConfig.getCharset(),
                alipayConfig.getAlipay_public_key(),
                alipayConfig.getSign_type());

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(alipayConfig.getReturn_url());
        alipayRequest.setNotifyUrl(alipayConfig.getNotify_url());

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + payBean.getTradeNo()+ "\","
                + "\"total_amount\":\"" + payBean.getTotalAmount() + "\","
                + "\"subject\":\"" + payBean.getSubject() + "\","
                + "\"body\":\"" + payBean.getBody() + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        try {
            return alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
            throw new RuntimeException("支付失败",e);
        }
    }
}
